#pragma once

#include "log.hpp"
#include <iostream>
#include <unistd.h>



// template<class T>
class Task
{
private:
    log lg;
public:
    Task(int sockfd, const uint16_t &port, const std::string &ip)
        : _sockfd(sockfd), _port(port), _ip(ip)
    {
    }
    void run()
    {
        char buffer[4096];
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client key#" << buffer << std::endl;
            std::string echo_string = "server reply: ";
            echo_string += buffer;

            n = write(_sockfd, echo_string.c_str(), echo_string.size());
            if (n < 0)
            {
                lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0) // 说明服务器把文件关闭了
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _ip.c_str(), _port, _sockfd);
        }
        else
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _ip.c_str(), _port);
        }
    }
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
};